//
//  MOFoodZhanDanViewController.m
//  MobileOffice
//
//  Created by 冰冰 on 2019/10/22.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MOFoodZhanDanViewController.h"
#import "MOFoodZhanDanViewCell.h"
#import "MORefreshNormalHeader.h"
#import "MORefreshGifFooter.h"
#import "MOFoodOrderListDetailViewController.h"

@interface MOFoodZhanDanViewController ()<UITableViewDelegate,UITableViewDataSource,XLsn0wPickerTimerDelegate,YPSwipeTableViewCellDelegate>

@property(nonatomic,strong)UIButton *dateButton;

@property(nonatomic,strong)NSString *dateStr;

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,assign)NSInteger currentPage;

@property(nonatomic,strong)UIView *headerView;

@property(nonatomic,strong)UILabel *inLabel;

@property(nonatomic,strong)UILabel *outLabel;

@property(nonatomic,strong) NSMutableArray *buttonArray;

@end

@implementation MOFoodZhanDanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNav];
    
    [self creatView];
    
}

-(void)creatView
{
    self.title = @"账单";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.tableHeaderView = self.headerView;
}


-(void)initNav
{
    self.dateStr = [NSString getCurrentTimesAndFormat:@"YYYY-MM"];
    
    self.dateButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 30)];
    [self.dateButton setTitle:[NSString getCurrentTimesAndFormat:@"YYYY-MM"] forState:UIControlStateNormal];
    self.dateButton.titleLabel.font = FONT_SIZE(13);
    [self.dateButton setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentRight)];
    [self.dateButton setTitleColor:KBlueColor_2C94FF forState:UIControlStateNormal];
    [self.dateButton addTarget:self action:@selector(clickDateMoney) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.dateButton];
}

-(void)initData
{
    NSString *postUrl = [NSString stringWithFormat:@"%@?authorization=%@",GETUSERACCOUNTS,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    NSDictionary *dic = @{
                          @"userName":[MOUser sharedMOUser].userName,
                          @"recipeTime":self.dateStr,
                          @"pageNo":[NSString stringWithFormat:@"%ld",(long)self.currentPage],
                          @"limit":@"10"
                          };
    [PPNetworkHelper POST:postUrl parameters:dic success:^(id responseObject) {
        NSLog(@"账单：%@",responseObject);

        if (self.currentPage==1) {
            self.dataArray = [NSMutableArray array];
        }
        NSArray *dataArray = [NSArray array];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            
            self.inLabel.text = [NSString stringWithFormat:@"收入：%@元",responseObject[@"add"]];
            self.outLabel.text = [NSString stringWithFormat:@"支出：%@元",responseObject[@"reduce"]];
            
            dataArray = responseObject[@"data"];
            for (int i = 0; i<dataArray.count; i++) {
                MOFoodZhanDanModel *model = [[MOFoodZhanDanModel alloc]init];
                model.typeStr = dataArray[i][@"type"];
                model.dateStr = dataArray[i][@"createTime"];
                model.orderId = dataArray[i][@"orderId"];
                model.priceStr = [NSString passNullForString:dataArray[i][@"amount"]];
                [self.dataArray addObject:model];
            }
        }else if ([responseObject isKindOfClass:[NSString class]]){
            NSDictionary *dataDic = [self dictionaryWithJsonString:responseObject];
            
            self.inLabel.text = [NSString stringWithFormat:@"收入：%@元",dataDic[@"add"]];
            self.outLabel.text = [NSString stringWithFormat:@"支出：%@元",dataDic[@"reduce"]];
            
            dataArray = dataDic[@"data"];
            for (int i = 0; i<dataArray.count; i++) {
                MOFoodZhanDanModel *model = [[MOFoodZhanDanModel alloc]init];
                model.typeStr = dataArray[i][@"type"];
                model.dateStr = dataArray[i][@"createTime"];
                model.orderId = dataArray[i][@"orderId"];
                model.priceStr = [NSString passNullForString:dataArray[i][@"amount"]];
                [self.dataArray addObject:model];
            }
        }
        
        if (dataArray.count==0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            [[ADShowMessage shareShowMessage] showTextOnly:@"暂无数据" showInView:self.view];
        }
        [self refreshEnding];
        
        
    } failure:^(NSError *error) {
        NSLog(@"账单：%@",[error localizedDescription]);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark -刷新，加载更多
//刷新
- (void)downloadAfaterDataSource{
    self.currentPage = 1;
    [self initData];
}

//加载更多
- (void)downloadBeforeDataSource{
    self.currentPage++;
    [self initData];
}

//刷新效果停止
- (void)refreshEnding{
    [self.tableView.mj_footer endRefreshing];
    [self.tableView.mj_header endRefreshing];
    [self.tableView reloadData];
}


-(void)clickDateMoney
{
    XLsn0wPickerTimer *pickerDate = [[XLsn0wPickerTimer alloc] init];
    pickerDate.maxComponentCount = 2;
    pickerDate.xlsn0wDelegate = self;
    [pickerDate show];
}

- (void)pickerTimer:(XLsn0wPickerTimer *)pickerTimer year:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    
    NSString *date = [NSString stringWithFormat:@"%ld-%02ld",(long)year,(long)month];
    self.dateStr = date;
    
    [self downloadAfaterDataSource];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier = @"Cell";
    MOFoodZhanDanViewCell *foodOrderListCell = [[MOFoodZhanDanViewCell alloc]cellCreat:cellIdentifier AndArray:self.buttonArray andTableView:tableView cellIndexPath:indexPath andType:0];
    foodOrderListCell.delegate = self;
    foodOrderListCell.model = self.dataArray[indexPath.section];
    return foodOrderListCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00000001;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma mark - YPSwipeTableViewCelldidSelectBtnWithTag 代理
- (void)YPSwipeTableViewCelldidSelectBtnWithTag:(NSInteger)tag andIndexPath:(NSIndexPath *)indexpath{
    MOFoodZhanDanModel *model = self.dataArray[indexpath.section];
    if (tag==0) {
        if ([model.typeStr integerValue]==0) {
            [[ADShowMessage shareShowMessage]showTextOnly:@"该类型为充值，没有订单！" showInView:self.view];
            return;
        }
        MOFoodOrderListDetailViewController *vc = [[MOFoodOrderListDetailViewController alloc]init];
        vc.orderId = model.orderId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark -懒加载
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - StatusBarAndNavigationBarHeight) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = KGrayColor_f8f8f8;
        
        _tableView.mj_header = [MORefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downloadAfaterDataSource)];
        _tableView.mj_footer = [MORefreshGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(downloadBeforeDataSource)];
        [_tableView.mj_header beginRefreshing];
    }
    return _tableView;
}

-(UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45)];
        _headerView.backgroundColor = KBlueColor_B7DAFF;
        
        for (int i = 0; i<2; i++) {
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2*i, 0, SCREEN_WIDTH/2, 45)];
            label.textAlignment = NSTextAlignmentCenter;
            label.font = FONT_SIZE(15);
            [_headerView addSubview:label];
            
            if (i==0) {
                self.inLabel = label;
            }else if (i==1){
                self.outLabel = label;
            }
        }
        
    }
    return _headerView;
}

-(NSMutableArray *)buttonArray
{
    UIButton *btn11 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 80)];
    btn11.backgroundColor = [UIColor whiteColor];
    [btn11 setTitle:@"订单详情" forState:UIControlStateNormal];
    [btn11 setTitleColor:KBlueColor_2C94FF forState:UIControlStateNormal];
    [btn11 setImage:[UIImage imageNamed:@"dingcan_detail"] forState:UIControlStateNormal];
    btn11.titleLabel.font = FONT_SIZE(12);
    btn11.userInteractionEnabled = NO;
    [btn11 SG_imagePositionStyle:(SGImagePositionStyleTop) spacing:5];
    
    
    UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    btn1.backgroundColor = KGrayColor_f8f8f8;
    [btn1 addSubview:btn11];
    
    _buttonArray = [[NSMutableArray alloc]initWithObjects:btn1, nil];
    
    return _buttonArray;
}

@end
